/**
 * Project Name:hyh-web
 * File Name:GlobalExceptionHandler.java
 * Package Name:com.hyh.configuration
 * Date:2018年8月31日下午4:52:36
 *
*/

package com.hyh.configuration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.hyh.result.Result;

/**
 * ClassName:GlobalExceptionHandler
 * Reason:	 TODO ADD REASON.
 * Date:     2018年8月31日 下午4:52:36
 * @author   huangyihao
 * @version  
 * @see 	 
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	
	@ExceptionHandler(Exception.class)
	public Result<String> handleException(Exception ex, HttpServletRequest request) {
		return new Result<>("9999", "对不起，出错啦！请联系技术人员！");
	}
	
	
	/**
	 * hibernate 验证异常
	 * 
	 * @param ex
	 * @param request
	 * @return
	 */
	@ExceptionHandler(BindException.class)
	public Result<String> handleBindException(BindException ex, HttpServletRequest request) {
		BindingResult bindingResult = ex.getBindingResult();
		FieldError fieldError = bindingResult.getFieldError();
		return new Result<>("9004", fieldError.getField() + ":" + fieldError.getDefaultMessage());
	}
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
		BindingResult bindingResult = ex.getBindingResult();
		FieldError fieldError = bindingResult.getFieldError();
		return new Result<>("9004", fieldError.getField() + ":" + fieldError.getDefaultMessage());
	}

	@ExceptionHandler(HttpMessageNotReadableException.class)
	public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex, HttpServletRequest request) {
		return new Result<>("9004", "请使用正确的json传参！");
	}
	
	/**
	 * requestParam 验证异常
	 * 
	 * @param ex
	 * @param request
	 * @return
	 */
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public Result<String> handleBindException(MissingServletRequestParameterException ex, HttpServletRequest request) {
		return new Result<>("9005", ex.getMessage());
	}
	
}
